import { assoc, isNil, pipe } from 'ramda';
import { createEntity } from '../database/middleware';
import { listEntities, storeLoadById } from '../database/middleware-loader';
import { BUS_TOPICS } from '../config/conf';
import { notify } from '../database/redis';
import { ENTITY_TYPE_MALWARE } from '../schema/stixDomainObject';
import { ABSTRACT_STIX_DOMAIN_OBJECT } from '../schema/general';
import { FROM_START, UNTIL_END } from '../utils/format';

export const findById = (context, user, malwareId) => {
  return storeLoadById(context, user, malwareId, ENTITY_TYPE_MALWARE);
};

export const findAll = (context, user, args) => {
  return listEntities(context, user, [ENTITY_TYPE_MALWARE], args);
};

export const addMalware = async (context, user, malware) => {
  const malwareToCreate = pipe(
    assoc('first_seen', isNil(malware.first_seen) ? new Date(FROM_START) : malware.first_seen),
    assoc('last_seen', isNil(malware.last_seen) ? new Date(UNTIL_END) : malware.last_seen),
    assoc('is_family', malware.is_family === true)
  )(malware);
  const created = await createEntity(context, user, malwareToCreate, ENTITY_TYPE_MALWARE);
  return notify(BUS_TOPICS[ABSTRACT_STIX_DOMAIN_OBJECT].ADDED_TOPIC, created, user);
};
